package com.hongtech.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 转换工具类
 */
public class BeanCopierUtils {

    private final static Logger logger = LoggerFactory.getLogger(BeanCopierUtils.class);

    /**
     * 实体内容转换
     *
     * @param source 源实体
     * @param target 目标实体Class
     * @return 返回目标实体内容
     */
    public static <T> T copyProperties(Object source, Class<T> target) {
        if (source == null) {
            return null;
        }
        T targetObject = null;
        try {
            targetObject = target.newInstance();
            BeanUtils.copyProperties(source, targetObject);
        } catch (Exception e) {
            logger.error("Bean内容转换错误", e);
        }
        return targetObject;
    }

    /**
     * 实体集合转换
     *
     * @param sourceList 源实体集合
     * @param target     目标实体Class
     * @return 返回目标实体集合
     */
    public static <T> List<T> copyPropertiesList(Collection<?> sourceList, Class<T> target) {
        if (sourceList == null) {
            return null;
        }
        List<T> targetList = new ArrayList<>(sourceList.size());
        try {
            for (Object source : sourceList) {
                T targetObject = target.newInstance();
                BeanUtils.copyProperties(source, targetObject);
                targetList.add(targetObject);
            }
        } catch (Exception e) {
            logger.error("List内容转换错误", e);
        }
        return targetList;
    }

}
